package com.zyasdk;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.IntentFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.zhuoyian.analysis.Analysis;
import com.zhuoyian.analysis.AnalysisBuilder;
import com.zhuoyian.analysis.AnalysisBuilder.DownLoadState;
import com.zhuoyian.analysis.common.AnalysisConsts;
import com.zhuoyian.dl.Download;
import com.zhuoyian.dl.listener.DownloadListener;
import com.zhuoyian.dl.util.DownloadParameter;
import com.zyasdk.broadcast.NetChangeReceive;
import com.zyasdk.handler.VersionHandler;
import com.zyasdk.model.Packages;
import com.zyasdk.service.VersionService;
import com.zyasdk.util.apk.ApkInstallUtil;
import com.zyasdk.util.res.CRUtil;
import com.zyasdk.util.root.RootUtil;

/**
 * 强制更新
 * 
 * @author Administrator
 */
public class VUpdateUtil {
	private static Dialog dialog;
	private static VersionHandler handler;
	private static NetChangeReceive netChangeReceive;

	/**
	 * 更新
	 * 
	 * @param context
	 */
	public static void update(Activity context) {
		handler = new VersionHandler(context);

		IntentFilter filter = new IntentFilter();
		filter.addAction(NetChangeReceive.CONNECTIVITY_CHANGE_ACTION);
		filter.setPriority(1000);
		netChangeReceive = new NetChangeReceive();
		context.registerReceiver(netChangeReceive, filter);
	}

	public static void reset() {
		if (handler == null) {
			return;
		}
		VersionService service = new VersionService(handler.mCon);
		service.GetNewVersions(handler);
	}

	public static void unRegister(Context context){
		if (netChangeReceive != null){
			context.unregisterReceiver(netChangeReceive);
		}
	}

	/**
	 * 下载新的版本
	 * 
	 * @param ver
	 */
	public static void download(Packages ver) {
		final long time = System.currentTimeMillis();
		Download.serialDlPointFile(ver.getPath(),
				DownloadParameter.TYPE_DEFAULT, ver, new DownloadListener() {

					@Override
					public void onDownload(DownloadParameter params, Object arg1) {
						switch (params.getDownState()) {
						case DownloadParameter.STATE_START:
							Packages v1 = (Packages) arg1;
							AnalysisBuilder ab = AnalysisBuilder.create()
									.putState(DownLoadState.ENTER)
									.putComeTime("" + time).putExitTime()
									.putStayTime("0").putUrl(v1.getPath());
							Analysis.getUpdateAnalysis().analysis(
									AnalysisConsts.SCENE_UPDATE,
									"" + v1.getOldVersion(),
									"" + v1.getVcode(), ab);

							break;
						case DownloadParameter.STATE_DOWING:
							break;
						case DownloadParameter.STATE_STOP:
							Download.serialDlPointFile(params.getUrl(),
									DownloadParameter.TYPE_DEFAULT);
							if (dialog != null) {
								dialog.dismiss();
								dialog = null;
							}
							break;
						case DownloadParameter.STATE_COMPLETE:
							if (dialog != null) {
								dialog.dismiss();
								dialog = null;
							}
							Packages v2 = (Packages) arg1;
							AnalysisBuilder a = AnalysisBuilder
									.create()
									.putState(DownLoadState.FINSH)
									.putComeTime("" + time)
									.putExitTime()
									.putStayTime(
											""
													+ (System
															.currentTimeMillis() - time)
													/ 1000)
									.putUrl(v2.getPath());
							Analysis.getUpdateAnalysis().analysis(
									AnalysisConsts.SCENE_UPDATE,
									"" + v2.getOldVersion(),
									"" + v2.getVcode(), a);

							// 更新版本
							if (RootUtil.isRoot()) {
								ApkInstallUtil.silentInstall(params
										.getLocalPath());
							} else {
								// 提示安装
								handler.obtainMessage(
										VersionHandler.UPDATE_VERSION,
										params.getLocalPath()).sendToTarget();
							}
							break;

						default:
							break;
						}
					}
				});
	}

	/**
	 * 提示更新对话框
	 * 
	 * @param context
	 */
	public static void hintUpdateVersion(final Activity context,
			final String localPath) {
		String btn = context.getString(CRUtil.getStringId(context,
				"zya_version_dialog_update_btn"));
		String title = context.getString(CRUtil.getStringId(context,
				"zya_version_dialog_title"));
		String okStr = context.getString(CRUtil.getStringId(context,
				"zya_version_dialog_update_btn"));
		// String cancelStr = context.getString(CRUtil.getStringId(context,
		// "zya_version_dialog_lbtn"));
		dialog = new Dialog(context, CRUtil.getStyleId(context,
				"loading_dialog"));
		View view = LayoutInflater.from(context).inflate(
				CRUtil.getLayoutId(context, "zya_dialog_layout"), null);
		view.findViewById(CRUtil.getId(context, "layout_zya_dialog_mess"))
				.setVisibility(View.GONE);

		dialog.setContentView(view);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		// 屏蔽返回键
		// dialog.setOnKeyListener(new OnKeyListener() {
		//
		// @Override
		// public boolean onKey(DialogInterface dialog, int keyCode,
		// KeyEvent event) {
		// if (keyCode == KeyEvent.KEYCODE_BACK
		// && event.getRepeatCount() == 0) {
		// return true;
		// }
		// return false;
		// }
		// });

		Button rightBtn = (Button) view.findViewById(CRUtil.getId(context,
				"btn_zya_dialog_right"));
		rightBtn.setVisibility(View.VISIBLE);
		rightBtn.setText(btn);
		// Button leftBtn = (Button) view.findViewById(CRUtil.getId(context,
		// "btn_zya_dialog_left"));
		// leftBtn.setVisibility(View.VISIBLE);
		// leftBtn.setText(cancelStr);
		// leftBtn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // 取消
		// if (dialog != null) {
		// dialog.cancel();
		// }
		// }
		// });
		rightBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 更新
				if (dialog != null) {
					dialog.cancel();
				}
				ApkInstallUtil.install(localPath, context);
			}
		});
		((TextView) view.findViewById(CRUtil.getId(context,
				"tv_zya_dialog_title"))).setText(title);
	}

}
